package com.hll.util;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.*;

/**
 * Created by Dec-23 on 2016/11/22.
 * 签名和验签工具类
 */
public class signUtils {



    /**
     * MD5生成签名字符串
     *
     * @param map
     *            需签名参数
     * @param key
     *            MD5key
     * @return
     */
    public static String MD5sign(Map<String, Object> map, String key) {
        String genSign = "";
        try {
            // 构建签名原文
            String signSrc = orgSignSrc(map);
            // MD5的方式签名,MD5(key+参数值1+参数值2+..+key)toLowerCase()
            String signStr=key+signSrc + key;
            //得到MD5
            genSign = MD5Encrypt.getMessageDigest(signStr).toLowerCase();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return genSign;
    }

    /**
     * 字典排序构建签名原文
     * @param map
     * @return
     */
    private static String orgSignSrc(Map<String, Object> map) {
        Collection<String> keyset= map.keySet();
        List<String> list = new ArrayList<String>(keyset);

        //对key键值按字典升序排序
        Collections.sort(list);
        String signStr ="";
        for (int i = 0; i < list.size(); i++) {
            signStr+=map.get(list.get(i));
            System.out.println(list.get(i)+"："+map.get(list.get(i)));
        }
        return signStr.toString();
    }

    /**
     * MD5验证签名
     * @param map
     * @param key
     * @param sign
     * @return
     */
    public static Boolean vlidateMD5sign(Map<String ,Object> map, String key,String sign) {
        String vsign=MD5sign(map,key);
        System.out.println("MD5验证签名生成的签名："+vsign);
        System.out.println("MD5验证签名生成的签名与原签名是否一致：sign=vsign true?false:"+(vsign.equals(sign)));
        if (vsign.equals(sign)){
            return true;
        }else{
            return false;
        }

    }
    public static void main(String[] args) {
        String signPara = "action=query&code=123123&mid=896&posId=腾瑞明管理员&posSeq=20170220154553244662&time=20170220154553&key=13609560e19c99beba298300435f8725";
        String _sign = DigestUtils.md5Hex(signPara).toUpperCase();
        System.out.println("MD5验证签名生成的签名："+_sign);
    }

}
